package com.itheima.reggie.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获SQL异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public R<String> doSQLException(SQLException e) {
        e.printStackTrace();
        String message = e.getMessage();
        Matcher matcher = Pattern.compile("'.*?'").matcher(message);
        if (message.contains("Duplicate entry") && matcher.find()) {
            String str = matcher.group(0);
            str = str.substring(1, str.length()-1);
            return R.error(str + "已存在");
        }
        if (message.contains("Data too long") && matcher.find()) {
            String column = matcher.group(0);
            column = column.substring(1, column.length() -1);
            return R.error(column + "数据超长");
        }
        return R.error(message);
    }

    /**
     * 处理自定义异常
     * @param ce
     * @return
     */
    @ExceptionHandler(CustomizeException.class)
    public R<String> doCustomizeException(CustomizeException ce) {
        return R.error(ce.getMessage());
    }
}
